Promises


A Promise in JavaScript is an object representing the eventual completion or failure of an asynchronous operation. Promises provide a cleaner, more flexible way to handle asynchronous operations compared to callbacks.

Creating a Promise

You can create a promise using the Promise constructor:

let myPromise = new Promise(function(resolve, reject) {
    // Producing code (may take some time)
    let success = true; // Simulating success or failure
    if (success) {
        resolve("Operation was successful!");
    } else {
        reject("Operation failed.");
    }
});

Consuming a Promise

You can consume a promise using the then and catch methods:

myPromise.then(function(value) {
    console.log(value); // "Operation was successful!"
}).catch(function(error) {
    console.log(error); // "Operation failed."
});

Chaining Promises

Promises can be chained to handle multiple asynchronous operations in sequence:

let promise = new Promise(function(resolve, reject) {
    setTimeout(function() {
        resolve(10);
    }, 1000);
});

promise.then(function(value) {
    console.log(value); // 10
    return value * 2;
}).then(function(value) {
    console.log(value); // 20
    return value * 3;
}).then(function(value) {
    console.log(value); // 60
}).catch(function(error) {
    console.log(error);
});

Promise States

A promise can be in one of three states:

Example with Child Elements

Here is an example demonstrating how to access and manipulate child elements:

// HTML
// 
//
Child 1
//
Child 2
//
let parent = document.getElementById('parent'); let children = parent.getElementsByClassName('child'); for (let i = 0; i < children.length; i++) { children[i].style.color = 'blue'; }

For more detailed information, you can check out resources like W3Schools[^1^][1] and MDN Web Docs[^2^][2].